<template>
    <client-only>
        <div class="tinymce-editor" :id="selectorId">
            <editor
                v-if="!reloading"
                v-model="myValue"
                :init="init"
                :disabled="disabled"
                @onClick="onClick"
            ></editor>
        </div>
    </client-only>
</template>

<script>
import Editor from '@tinymce/tinymce-vue'
import { getUUID } from '~/plugins/tools'

let tinymce
if (process.client) {
    tinymce = require('tinymce/tinymce')
    require('tinymce/themes/silver/theme')
    require('tinymce/plugins/image')
    require('tinymce/plugins/link')
    require('tinymce/plugins/media')
    require('tinymce/plugins/table')
    require('tinymce/plugins/lists')
    require('tinymce/plugins/contextmenu')
    require('tinymce/plugins/wordcount')
    require('tinymce/plugins/colorpicker')
    require('tinymce/plugins/textcolor')
    require('tinymce/plugins/fullscreen')
    require('tinymce/icons/default')
}

export default {
    name: 'TinymceEditor',
    components: {
        Editor
    },
    props: {
        value: {
            type: String,
            required: false,
            default: ''
        },
        triggerChange: {
            type: Boolean,
            default: false,
            required: false
        },
        disabled: {
            type: Boolean,
            default: false
        },
        plugins: {
            type: [String, Array],
            default:
        // 'lists image link media table textcolor wordcount contextmenu fullscreen',
        'lists image link media table wordcount fullscreen'
        },
        toolbar: {
            type: [String, Array],
            default:
        'undo redo |  formatselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | lists link unlink image table | removeformat | fullscreen',
            branding: false
        },
        width: {
            type: String,
            default: 'auto'
        },
        height: {
            type: Number,
            default: 300
        },
        cosPath: {
            type: String,
            required: true
        }
    },
    data () {
        return {
            // 初始化配置
            selectorId: new Date().getTime(),
            init: {
                language_url: '/tinymce/langs/zh_CN.js',
                language: 'zh_CN',
                skin_url: '/tinymce/skins/lightgray',
                width: this.width,
                height: this.height,
                object_resizing: false,
                selector: 'tinymce-editor',
                content_css: '/tinymce/skins/lightgray/content.min.css',
                content_style: `
          .mce-content-body {
            width: ${this.width};
            overflow-x: hidden;
          }
          .mce-content-body table {
            width: auto !important;
          }
        `,
                plugins: this.plugins,
                toolbar: this.toolbar,
                branding: false,
                menubar: false,
                toolbar_drawer: false,
                statusbar: false, // 隐藏底部状态栏
                images_upload_handler: (blobInfo, success) => {
                    const arr = blobInfo.filename().split('.')
                    const fileType = arr[arr.length - 1]
                    const _path = '/' + this.cosPath + '/' + this.$service.dateFormatter('yyyy-MM-dd') + '/'
                    this.$service.getAuthor({ Method: 'POST', Pathname: '/' })
                        .then((info) => {
                            const formData = new FormData()
                            const _key = _path + getUUID() + '.' + fileType
                            formData.append('signature', info.Authorization)
                            formData.append('x-cos-security-token', info.XCosSecurityToken)
                            formData.append('Content-Type', '')
                            formData.append('key', _key)
                            formData.append('dir', _path)
                            formData.append('host', this.$staticUrl)
                            formData.append('file', blobInfo.blob(), blobInfo.filename())
                            this.$ApiServer.uploadFileCos(formData).then((res) => {
                                if (res === '') {
                                    success(this.$staticUrl + _key)
                                } else {
                                    this.$message.error('上传失败')
                                }
                            }).catch(() => {
                                this.$message.error('上传失败')
                            })
                        }).catch(() => {
                            this.$message.error('上传失败')
                        })
                }
            },
            myValue: '',
            reloading: false
        }
    },
    watch: {
        value: {
            immediate: true,
            handler (newValue) {
                this.myValue = newValue == null ? '' : newValue
            }
        },
        myValue: {
            immediate: true,
            handler (newValue) {
                if (this.triggerChange) {
                    this.$emit('change', newValue)
                } else {
                    this.$emit('input', newValue)
                }
            }
        }
    },
    mounted () {
        this.initATableChangeAutoReload()
    },
    methods: {
        reload () {
            this.reloading = true
            this.$nextTick(() => (this.reloading = false))
        },

        onClick (e) {
            this.$emit('onClick', e, tinymce)
        },
        // 可以添加一些自己的自定义事件，如清空内容
        clear () {
            this.myValue = ''
        },
        getVmParentByName (vm, name) {
            const parent = vm.$parent
            if (parent && parent.$options) {
                if (parent.$options.name === name) {
                    return parent
                } else {
                    const res = this.getVmParentByName(parent, name)
                    if (res) {
                        return res
                    }
                }
            }
            return null
        },
        // 判断父级是否是<a-tabs/>组件
        initATableChangeAutoReload () {
            const tabs = this.getVmParentByName(this, 'ATabs')
            const tabPane = this.getVmParentByName(this, 'ATabPane')
            const model = this.getVmParentByName(this, 'AFormModel')
            if (tabs && tabPane) {
                const currentKey = tabPane.$vnode.key
                tabs.$on('change', (key) => {
                    if (currentKey === key) {
                        this.reload()
                    }
                })
            } else if (model) {
                this.reload()
            }
        }
    }
}
</script>
<style lang="less" scoped></style>
